/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.applet.Applet;
import java.awt.GridLayout;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


/**
 *
 * @author yoga1290
 */
class RobReq
{
    private Robot rob;
    public RobReq()
    {
        try
        {
            rob=new Robot();
        }catch(Exception e){System.err.println(e);}
    }
    public void req(String txt)
    {
        
    }
}
class jfr implements ActionListener,Runnable
{
    public JFrame mfr;
    public JPanel jp1;
    public JTextField port;
    public JTextField pw;
    public JButton ok,exit;
    private Thread runner;
    public jfr()
    {
        
            mfr = new JFrame("Screen Pointer/Youssef Gamil");
            mfr.setSize(300, 300);
            mfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mfr.setLayout(new GridLayout(3, 2));
            mfr.add(new JLabel("IP Address:"));
            try {
            mfr.add(new JLabel(InetAddress.getLocalHost().getHostAddress()));
            } catch (UnknownHostException ex) {
                System.err.println(ex);
            //Logger.getLogger(jfr.class.getName()).log(Level.SEVERE, null, ex);
            }
            
//            port=new JTextField("80");
  //          mfr.add(new JLabel("Server Port:"));
    //        mfr.add(port);

            pw=new JTextField();
            mfr.add(new JLabel("Pass Key:"));
            mfr.add(pw);

            ok=new JButton("OK");
            ok.addActionListener(this);
            exit=new JButton("Exit");
            exit.addActionListener(this);
            mfr.add(ok);mfr.add(exit);
            mfr.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==ok)
        {
            if(runner==null)
            {
                runner=new Thread(this);
                runner.start();
            }
        }
        else
            System.exit(0);
//        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void run() {
        try{
                //Integer.parseInt(port.getText())
            ServerSocket ss = new ServerSocket(1290);
            while(true){
               // display("listening again ** port: "+port+"\n");
                Socket s = ss.accept();
                new Thread(new FileRequest(s,pw.getText())).start();
                //display("got a file request \n");
            }
            }catch(Exception ex){System.err.println(ex);}
//        throw new UnsupportedOperationException("Not supported yet.");
    }
}
class FileRequest implements Runnable{
    public Robot rob;
    private String keyy;
    public boolean send=true;

    FileRequest(Socket s,String k){
     //   this.app=app;
        client = s;
        keyy=k;
    } //*/
    public void run(){

        if(requestRead()){
            if(fileOpened()){
                constructHeader();
                if(fileSent()){
// app.display("*File: "+fileName+" File Transfer Complete*Bytes Sent:"+bytesSent+"\n");
                }
            }
        }
          try{
            dis.close();
            client.close();
        }catch(Exception e){}

    }


    private boolean fileSent()
    {
        try{
DataOutputStream clientStream = new DataOutputStream
(new BufferedOutputStream(client.getOutputStream()));
            clientStream.writeBytes(header);
      //      app.display("******** File Request *********\n"+
          //              "******* "+ fileName +"*********\n"+header);
            int i;
            bytesSent = 0;
            while((i=requestedFile.read()) != -1){
                clientStream.writeByte(i);
                bytesSent++;
            }
            clientStream.flush();
            clientStream.close();
		 }catch(IOException e){return false;}
		 return true;

    }
    private boolean fileOpened()
    {
//        ByteInputStream bis=new ByteInputStream("".getBytes(), 0);
  //      DataInputStream dis=new DataInputStream(bis);
        if(send)
        {
        try{
requestedFile = new DataInputStream(new BufferedInputStream
((this.getClass().getResourceAsStream("/"+fileName))));
                fileLength = requestedFile.available();
     //           app.display(fileName+" is "+fileLength+" bytes long.\n");
            }catch(FileNotFoundException e){
                if(fileName.equals("filenfound.html")){return false;}
                fileName="filenfound.html";
                if(!fileOpened()){return false;}
            }catch(Exception e){return false;}

        }
        else
        {
            try{
            requestedFile = new DataInputStream(new ByteArrayInputStream("".getBytes()));
                fileLength = requestedFile.available();
            }catch(Exception e){return false;}
        }
			return true;

    }
    private boolean requestRead()
    {
         try{
            //Open inputStream and read(parse) the request
            dis = new DataInputStream(client.getInputStream());
            String line;
            send=true;
            while((line=dis.readLine())!=null){

                StringTokenizer tokenizer = new StringTokenizer(line," ");
                if(!tokenizer.hasMoreTokens()){ break;}

                        if(tokenizer.nextToken().equals("GET")){

                            fileName = tokenizer.nextToken();
                            if(fileName.equals("/")){
                                fileName = "index.html";
                            }else{
                                fileName = fileName.substring(1);
                                if(fileName.indexOf('?')!=-1)
                                {
                                    if(!fileName.substring(0,fileName.indexOf('?')).equals(keyy)) return false;
                                  //  System.out.println(fileName+"\t"+keyy);
                                    send=false;
                                    try{
                                    if(rob==null)   rob=new Robot();
                                    if(fileName.indexOf('=')!=-1)   rob.mouseMove(Integer.parseInt(fileName.substring(fileName.indexOf('=')+1,fileName.indexOf(',')) )
                                            ,Integer.parseInt(fileName.substring(fileName.lastIndexOf('=')+1,fileName.length()) ) );
                                    else if(fileName.indexOf("lc")!=-1){ rob.mousePress(InputEvent.BUTTON1_MASK);rob.mouseRelease(InputEvent.BUTTON1_MASK);}
                                    else
                                        { rob.mousePress(InputEvent.BUTTON3_MASK);rob.mouseRelease(InputEvent.BUTTON3_MASK);}
                                    }catch(Exception e){System.err.println(e);}
                                    fileName=fileName.substring(0,fileName.indexOf('?'));
                                }
                            }

                        }

            }

         }catch(Exception e){

            return false;
         }
     //      app.display("finished file request");

         return true;
    }


    private void constructHeader(){
        String contentType;
        if((fileName.toLowerCase().endsWith(".jpg"))||(fileName.toLowerCase().endsWith(".jpeg"))
||(fileName.toLowerCase().endsWith(".jpe"))){contentType = "image/jpg";}
        else if((fileName.toLowerCase().endsWith(".gif"))){contentType = "image/gif";}
        else if((fileName.toLowerCase().endsWith(".htm"))||
		(fileName.toLowerCase().endsWith(".html"))){contentType = "text/html";}
        else if((fileName.toLowerCase().endsWith(".qt"))||
		(fileName.toLowerCase().endsWith(".mov"))){contentType = "video/quicktime";}
        else if((fileName.toLowerCase().endsWith(".class"))){contentType = "application/octet-stream";}
        else if((fileName.toLowerCase().endsWith(".mpg"))||
(fileName.toLowerCase().endsWith(".mpeg"))||(fileName.toLowerCase().endsWith(".mpe")))
{contentType = "video/mpeg";}
        else if((fileName.toLowerCase().endsWith(".au"))||(fileName.toLowerCase().endsWith(".snd")))
            {contentType = "audio/basic";}
        else if((fileName.toLowerCase().endsWith(".wav")))
            {contentType = "audio/x-wave";}
        else {contentType = "text/plain";} //default

        header = "HTTP/1.0 200 OK\n"+
                 "Allow: GET\n"+
                 "MIME-Version: 1.0\n"+
                 "Server : HMJ Basic HTTP Server\n"+
                 "Content-Type: "+contentType + "\n"+
                 "Content-Length: "+ fileLength +
                 "\n\n";
    }

  //  private Serve app;
    private Socket client;
    private String fileName,header;
    private DataInputStream requestedFile, dis;
	private int fileLength, bytesSent;

}
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new jfr();

        // TODO code application logic here
    }

}
